#!/usr/bin/env python
#-*- coding:utf-8 -*-

'''
    author: cold night
    email : wh_linux@126.com
    date  : 2012-08-06 11:21
    mongo数据库操作模块
'''


from model.get_db import get_db
from model.common import not_empty, get_cate
from datetime import datetime
from bson.objectid import ObjectId

__all__=['article_post', 'article_edit', 'article_del', 'category',
         'category_edit', 'category_del', 'comment_add', 'comment_del']
db = get_db()
POST = 'posts'
CATE = 'categories'
COMM = 'comments'


def _del(postid, collection):
    '''
        删除,可单独也可批量删除
    '''
    if type(postid) == str :
        if ',' in postid:
            for _id in postid.split(','):
                db[collection].remove({"_id":ObjectId(_id)})
        else:
            db[collection].remove({"_id":ObjectId(postid)})
    elif type(postid) in (list, tuple):
        for _id in postid:
            db[collection].remove({"_id":ObjectId(_id)})
    else:
        raise ValueError("post id must be string/list/tuple")



def article_post(article_dict):
    '''
    处理文章提交
    '''
    not_empty(article_dict)
    cate = article_dict.get("categories", None)
            
    article_dict['categories'] = get_cate(cate)
    article_dict.update(date = datetime.now(), views = 0, comments = 0)
    result = db[POST].insert(article_dict, safe=True)
    for c in cate:
        db[CATE].update({"_id":ObjectId(c)},{"$inc":{"artnum":1}})
    return result


def article_edit(postid, article_dict):
    '''
        处理文章编辑
    '''
    not_empty(postid, article_dict)
    cate = article_dict.get("caetgories", None)
    article_dict.update(lastdate = datetime.now())
    db[POST].update({"_id":ObjectId(postid)}, {"$set":article_dict})



def article_del(postid):
    '''
        删除文章
    '''
    not_empty(postid)
    _del(postid, POST)    


    
def category(name):
    '''
        分类目录
    '''
    not_empty(name)
    _t = db[CATE].find_one({"name":name})
    if _t:
        return False
    else:
        return db[CATE].insert({"name":name, "artnum":0})
        
    

def category_edit(_id, name):
    not_empty(_id, name)
    db[CATE].update({'_id':ObjectId(_id)}, {"$set":{'name':name}})

    
def category_del(cateid):
    '''
    删除分类目录
    '''
    not_empty(cateid)
    _del(cateid, CATE)
    #TODO 删除所有使用此分类的文章里的此目录
    db.POSTS.update({"categories":cateid},{"$pull":{"categories":cateid}})
    


def comment_add(artid, comment_dict, commid=None):
    '''
        添加评论
    '''
    not_empty(artid, comment_dict)
    comment_dict.update(date = datetime.now(), artid=artid, parentid=commid)
    db[COMM].insert(comment_dict, safe=True)
    db[POST].update({"_id":ObjectId(artid)}, {"$inc":{"comments":1}})

    
def comment_del(commid, delsub = False):
    '''
    删除评论
    Arguments:
    `delsub`: 是否删除子评论
    '''
    
    _ids = []
    if type(commid) == str:
        if ',' in commid:
            for _id in commid.split(',') :
                _ids.append(_id)
        else:
            _ids.append(commid)
    elif type(commid) in (list, tuple):
        _ids = commid
    else:
        raise ValueError("commid must be str/list/tupe")
    
    for _id in _ids:
        artid = db[COMM].find_one(dict(_id=ObjectId(commid))).get('artid')
        if delsub:
            db[COMM].remove({"parentid":_id})
        else:
            db[COMM].update({"parentid":_id}, {"$set":{"parentid":None}})
        db[POST].update(dict(_id=ObjectId(artid)), {"$inc":{"comments":-1}})

    _del(commid, COMM)
